import axios from 'axios';
import { message } from 'antd';
import type { ResponseData } from './types';

// 创建 axios 实例
const axiosInstance = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 创建请求方法
const request = {
  get: <T>(url: string) => {
    return axiosInstance.get<any, T>(url);
  },
  post: <T>(url: string, data: any) => {
    return axiosInstance.post<any, T>(url, data);
  },
  put: <T>(url: string, data: any) => {
    return axiosInstance.put<any, T>(url, data);
  },
  delete: <T>(url: string) => {
    return axiosInstance.delete<any, T>(url);
  },
};



// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    message.error('请求发送失败');
    return Promise.reject(error);
  }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    return response.data;
  },
  (error) => {
    // 对响应错误做点什么
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未授权，跳转到登录页
          window.location.href = '/login';
          break;
        case 403:
          message.error('没有权限访问');
          break;
        case 404:
          message.error('请求的资源不存在');
          break;
        case 500:
          message.error('服务器错误');
          break;
        default:
          message.error('网络错误');
      }
    } else {
      message.error('网络连接失败');
    }
    return Promise.reject(error);
  }
);

export default request; 